import { _decorator, Component, Node, tween, v3, SpriteFrame, director, ProgressBar, BoxCollider2D, Contact2DType, RigidBody2D, v2, Button, Camera, UITransform, assetManager, math, Tween } from 'cc';
import { DataManager } from '../Public/DataManager';
const { ccclass, property } = _decorator;

@ccclass('StartScript')
export class StartScript extends Component {
    /**兔子 */
    @property({ displayName: '兔子', type: Node })
    rabbit: Node = null;
    /**适龄提醒 */
    @property({ displayName: '适龄提醒', type: Node })
    ageTip: Node = null;
    /**开始按钮 */
    @property({ displayName: '开始按钮', type: Node })
    startBtn: Node = null;
    /**健康提醒 */
    @property({ displayName: '健康提醒', type: Node })
    healthTip: Node = null;
    /**汽车 */
    @property({ displayName: '汽车', type: Node })
    car: Node = null;
    /**加载页面 */
    @property({ displayName: '加载页面', type: Node })
    loadPage: Node = null;
    /**进度条 */
    @property({ displayName: '进度条', type: ProgressBar })
    bar: ProgressBar = null;
    @property(Camera)
    camera: Camera = null;
    isCome: boolean = false;
    BundleNum: number = 0;
    t: Tween<Node> = null;
    onLoad() {
        assetManager.loadBundle(`source/a`, (e, a) => { if (e) { return; } this.BundleNum++; });
        assetManager.loadBundle(`source/b`, (e, a) => { if (e) { return; } this.BundleNum++; });
        assetManager.loadBundle(`source/c`, (e, a) => { if (e) { return; } this.BundleNum++; });
        assetManager.loadBundle(`source/d`, (e, a) => { if (e) { return; } this.BundleNum++; });
        assetManager.loadBundle(`source/e`, (e, a) => { if (e) { return; } this.BundleNum++; });
    }

    start() {
        const self = this;
        try {
            this.loginToWX();
            const { query } = wx.getLaunchOptionsSync();
            // console.log('game_user_id :>> ', query.game_user_id);
            // wx.login({
            //     success (res) {
            //       console.log('res.code :>> ', res.code);
            //     }
            //   })
        } catch (error) {
            console.log('error', error);
        }
        let act = false;
        this.t = tween(this.rabbit).by(5, { position: v3(Math.abs(this.rabbit.position.x) * 2) }, {
            onUpdate(t?, ratio?) {
                if (ratio > 0.5 && (!act)) {
                    act = true;
                    self.CarrotRoll();
                }
            },
            onComplete() {
                self.ageTip.active = false;
                self.healthTip.active = false;
                const t = setTimeout(() => {
                    tween(self.startBtn).to(0.5, { scale: v3(0.5, 0.5, 1) }, {
                        onComplete() {
                            if (self.isCome)
                                self.startGame();
                        }
                    }).start();
                    clearTimeout(t);
                }, 100);
            }
        }).start();
    }
    /**微信登陆 */
    loginToWX() {
        const self = this;
        wx.login({
            success: (s) => {
                if (s.code) {
                    wx.request({
                        url: 'https://2857e2g653.imdo.co/index.php/tpp/getUser',
                        data: {
                            code: s.code
                        },
                        header: {
                            'content-type': `application/x-www-form-urlencoded`,
                        },
                        method: `post`,
                        fail(e) {
                            console.log(e);
                            setTimeout(() => {
                                self.startGame();
                            }, 1000);
                        },
                        success(res) {
                            console.log('res', res);
                            const { game_user_id, head_portrait, level, name, token, node_ids, clearance_ids, user_id, openid, create_time } = res.data.data
                            DataManager.Instance.openid = openid;
                            if (res.data.code === 200) {
                                DataManager.Instance.token = token;
                                DataManager.Instance.game_user_id = game_user_id;
                                DataManager.Instance.head_portrait = head_portrait;
                                DataManager.Instance.level = level;
                                DataManager.Instance.name = name;
                                DataManager.Instance.node_ids = node_ids;
                                DataManager.Instance.clearance_ids = clearance_ids;
                                DataManager.Instance.user_id = user_id;
                                DataManager.Instance.nodeLens = node_ids ? node_ids.match(/\d+/g).length : 0;
                                DataManager.Instance.create_time = create_time;
                                self.isCome = true;
                                if (self.BundleNum >= 5) {
                                    self.t.stop();
                                    self.startGame();
                                }
                                try {
                                    wx.setUserCloudStorage({
                                        KVDataList: [{ key: `s`, value: `${DataManager.Instance.nodeLens}` }],
                                        success: (res) => {
                                            console.log('成功', res);
                                        },
                                        fail: (res) => {
                                            console.log('失败', res);
                                        }
                                    })
                                } catch (error) {
                                    console.log(error);
                                }
                            }
                            else {
                                self.getUserMes(openid, 0);
                            }
                        }
                    })
                    // console.log('s.code', s.code);
                }
            },
        })
    }
    /**微信获取用户信息 */
    getUserMes(openid: string, num: number) {
        const { x, y } = this.startBtn.getWorldPosition();
        const self = this;
        const height = wx.getWindowInfo().windowHeight;
        wx.getSetting({
            success(re) {
                if (re.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                        success: function (res) {
                            console.log(res.userInfo);
                            if (num) {
                                self.startGame();
                            }
                            else {
                                const { nickName, avatarUrl } = res.userInfo
                                self.regUserMes(nickName, avatarUrl, openid);
                            }
                        }
                    })
                } else {
                    // 否则，先通过 wx.createUserInfoButton 接口发起授权
                    let button = wx.createUserInfoButton({
                        type: 'image',
                        style: {
                            top: height - y,
                            left: x - 115,
                            width: 230,
                            height: 113.5,
                            // backgroundColor: '#ff0000',
                        }
                    })
                    button.onTap((res) => {
                        // 用户同意授权后回调，通过回调可获取用户头像昵称信息
                        console.log(res.userInfo);
                        if (num) {
                            self.startGame();
                        }
                        else {
                            const { nickName, avatarUrl } = res.userInfo
                            button.hide();
                            self.regUserMes(nickName, avatarUrl, openid);
                        }
                    })
                }
            }
        })
    }
    /**微信注册 */
    regUserMes(nickname: string, portrait: string, openid: string) {
        const self = this;
        // console.log('openid', openid);
        wx.request({
            url: 'https://2857e2g653.imdo.co/index.php/tpp/signIn',
            data: {
                nickname: nickname,
                portrait: portrait,
                openid: openid,
                username: nickname,
            },
            header: {
                'content-type': `application/x-www-form-urlencoded`,
            },
            method: `post`,
            fail(e) {
                console.log(e);
            },
            success(e) {
                const { game_user_id, head_portrait, level, name, token, node_ids, clearance_ids, user_id, create_time } = e.data.data
                DataManager.Instance.token = token;
                DataManager.Instance.game_user_id = game_user_id;
                DataManager.Instance.head_portrait = head_portrait;
                DataManager.Instance.level = level;
                DataManager.Instance.name = name;
                DataManager.Instance.node_ids = node_ids;
                DataManager.Instance.clearance_ids = clearance_ids;
                DataManager.Instance.user_id = user_id;
                DataManager.Instance.nodeLens = node_ids ? node_ids.match(/\d+/g).length : 0;
                DataManager.Instance.create_time = create_time;
                setTimeout(() => {
                    self.startGame();
                }, 100);
                try {
                    wx.setUserCloudStorage({
                        KVDataList: [{ key: `s`, value: `${DataManager.Instance.nodeLens}` }],
                        success: (res) => {
                            console.log('成功', res);
                        },
                        fail: (res) => {
                            console.log('失败', res);
                        }
                    })
                } catch (error) {
                    console.log(error);
                }
            }
        })
    }
    /**游戏开始 */
    startGame() {
        this.loadPage.active = true;
        const { x, y, z } = this.car.getPosition();
        director.preloadScene(`MainScene`, (a, b) => {
            this.bar.progress = a / b;
            this.car.setPosition(v3(x + Math.abs(x * 2) * (a / b), y, z));
        }, (e) => {
            director.loadScene(`MainScene`);
        })
    }
    /**胡罗卜掉落动作 */
    CarrotRoll() {
        this.startBtn?this.startBtn.active = true:null;
        const Rigid = this.startBtn?this.startBtn.getComponent(RigidBody2D):null;
        const Collider = this.startBtn?this.startBtn.getComponent(BoxCollider2D):null;
        Rigid?Rigid.type = 2:null;
        Collider?Collider.on(Contact2DType.BEGIN_CONTACT, this.CarrotCollider, this):null;
    }
    /**碰撞回调 */
    CarrotCollider() {
        setTimeout(() => {
            const Rigid = this.startBtn.getComponent(RigidBody2D);
            Rigid.type = 0;
            tween(this.startBtn).to(1, { eulerAngles: v3() }).start();
        }, 100);
    }

}

